package cn.lzc.jl.service.conf.http;

import java.io.IOException;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import cn.lzc.jl.service.util.codec.RequestDecode;

/**
 * 
 * <入参判断是否需要解密>
 * <读取配置判断是否需要解密>
 * 
 * @author  sunliang
 * @version  [版本号, 2018年9月4日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@ControllerAdvice(basePackages = "cn.lzc.jl.rest.test")
public class RequestBodyAdviceHandle implements RequestBodyAdvice
{
    private static final Logger logger = LoggerFactory.getLogger(RequestBodyAdviceHandle.class);
    
    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
        Type type, Class<? extends HttpMessageConverter<?>> aClass)
    {
        return body;
    }
    
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type,
        Class<? extends HttpMessageConverter<?>> aClass)
        throws IOException
    {
        try
        {
            boolean encode = false;
            if (methodParameter.getMethod().isAnnotationPresent(RequestDecode.class))
            {
                //获取注解配置的包含和去除字段
                RequestDecode serializedField = methodParameter.getMethodAnnotation(RequestDecode.class);
                //入参是否需要解密
                encode = serializedField.inDecode();
            }
            if (encode)
            {
                logger.info("method :【" + methodParameter.getMethod().getName() + "】返回数据解密");
                return new HttpInputMessageHandle(inputMessage);
            }
            else
            {
                return inputMessage;
            }
        }
        catch (Exception e)
        {
            logger.error("method :【" + methodParameter.getMethod().getName() + "】返回数据解密出现异常：" + e.getMessage());
            return inputMessage;
        }
    }
    
    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
        Type type, Class<? extends HttpMessageConverter<?>> aClass)
    {
        return body;
    }
    
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass)
    {
        return true;
    }
    
}
